#include "dlginflation.h"

#include <iostream>

const int MIN_BUFF = 500;    //minimum size of buffered data to read on serial 

QStringList messages;//debug purposes only - filled in the constructor - used in the update widgets func

const QString OPENED("open");
const QString CLOSED("closed");
const QString PULSED("pulsed");

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
///
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
DlgInflation::DlgInflation(QWidget *parent)
    : QDialog( parent, Qt::Window |Qt::FramelessWindowHint  ),
    m_bSequenceOn(false),
    m_outStream(NULL),
    m_inStream(NULL),
    m_serial(NULL)
{
	ui.setupUi(this);
    setWindowState(Qt::WindowMaximized);
//	Qt::WindowFlags flags = 0;
//	flags |= Qt::WindowMinimizeButtonHint;
//	setWindowFlags(flags);
    setGeometry(0,0,1280, 1069);
    qDebug()<<"height:"<<geometry().height();
	//setWindowIcon(QApplication::windowIcon ());
    


	//put the background on the widget
	this->setAutoFillBackground(true);
    QPixmap bgpixmap = QPixmap(":/images/modules/servcon/inflation/bkg_inflationdlg.png");
	QPalette p = this->palette();
	p.setBrush(this->backgroundRole(),QBrush(bgpixmap));
	this->setPalette(p);
	
	//decorate the buttons
	ui.styledButtonExitManualMode->replaceStatePixmap(PStyledButton::disabled, QPixmap(":/images/modules/servcon/inflation/btn_exit_manual_mode_disabled.png"));
	ui.styledButtonExitManualMode->replaceStatePixmap(PStyledButton::off, QPixmap(":/images/modules/servcon/inflation/btn_exit_manual_mode_inactive.png"));
	ui.styledButtonExitManualMode->replaceStatePixmap(PStyledButton::on_pressed, QPixmap(":/images/modules/servcon/inflation/btn_exit_manual_mode_pressed.png"));//illeagal state
	ui.styledButtonExitManualMode->replaceStatePixmap(PStyledButton::off_pressed, QPixmap(":/images/modules/servcon/inflation/btn_exit_manual_mode_pressed.png"));//illeagal state
	ui.styledButtonExitManualMode->replaceStatePixmap(PStyledButton::on, QPixmap(":/images/modules/servcon/inflation/btn_exit_manual_mode_active.png"));//illeagal state
	
	ui.styledButtonHoseClampOpen->replaceStatePixmap(PStyledButton::disabled, QPixmap(":/images/modules/servcon/inflation/btn_open_hc_disabled.png"));
	ui.styledButtonHoseClampOpen->replaceStatePixmap(PStyledButton::off, QPixmap(":/images/modules/servcon/inflation/btn_open_hc_inactive.png"));
	ui.styledButtonHoseClampOpen->replaceStatePixmap(PStyledButton::on_pressed, QPixmap(":/images/modules/servcon/inflation/btn_open_hc_pressed.png"));
	ui.styledButtonHoseClampOpen->replaceStatePixmap(PStyledButton::off_pressed, QPixmap(":/images/modules/servcon/inflation/btn_open_hc_pressed.png"));
	ui.styledButtonHoseClampOpen->replaceStatePixmap(PStyledButton::on, QPixmap(":/images/modules/servcon/inflation/btn_open_hc_active.png"));//illeagal state
	
	ui.styledButtonInflationValveControl->replaceStatePixmap(PStyledButton::disabled, QPixmap(":/images/modules/servcon/inflation/btn_stop_sequence_disabled.png"));
	ui.styledButtonInflationValveControl->replaceStatePixmap(PStyledButton::off, QPixmap(":/images/modules/servcon/inflation/btn_start_sequence_inactive.png"));
	ui.styledButtonInflationValveControl->replaceStatePixmap(PStyledButton::on_pressed, QPixmap(":/images/modules/servcon/inflation/btn_start_sequence_pressed.png"));
	ui.styledButtonInflationValveControl->replaceStatePixmap(PStyledButton::off_pressed, QPixmap(":/images/modules/servcon/inflation/btn_stop_sequence_pressed.png"));
	ui.styledButtonInflationValveControl->replaceStatePixmap(PStyledButton::on, QPixmap(":/images/modules/servcon/inflation/btn_stop_sequence_active.png"));//illeagal state

	ui.styledButtonMainTankValveOpen->replaceStatePixmap(PStyledButton::disabled, QPixmap(":/images/modules/servcon/inflation/btn_close_disabled.png"));
	ui.styledButtonMainTankValveOpen->replaceStatePixmap(PStyledButton::off, QPixmap(":/images/modules/servcon/inflation/btn_close_inactive.png"));
	ui.styledButtonMainTankValveOpen->replaceStatePixmap(PStyledButton::on_pressed, QPixmap(":/images/modules/servcon/inflation/btn_close_pressed.png"));
	ui.styledButtonMainTankValveOpen->replaceStatePixmap(PStyledButton::off_pressed, QPixmap(":/images/modules/servcon/inflation/btn_close_pressed.png"));
	ui.styledButtonMainTankValveOpen->replaceStatePixmap(PStyledButton::on, QPixmap(":/images/modules/servcon/inflation/btn_close_active.png"));//illeagal state

	ui.styledButtonThrusterValveOpen->replaceStatePixmap(PStyledButton::disabled, QPixmap(":/images/modules/servcon/inflation/btn_close_disabled.png"));
	ui.styledButtonThrusterValveOpen->replaceStatePixmap(PStyledButton::off, QPixmap(":/images/modules/servcon/inflation/btn_close_inactive.png"));
	ui.styledButtonThrusterValveOpen->replaceStatePixmap(PStyledButton::on_pressed, QPixmap(":/images/modules/servcon/inflation/btn_close_pressed.png"));
	ui.styledButtonThrusterValveOpen->replaceStatePixmap(PStyledButton::off_pressed, QPixmap(":/images/modules/servcon/inflation/btn_close_pressed.png"));
	ui.styledButtonThrusterValveOpen->replaceStatePixmap(PStyledButton::on, QPixmap(":/images/modules/servcon/inflation/btn_close_active.png"));//illeagal state

	connect(ui.styledButtonExitManualMode, SIGNAL(clicked(bool)), this, SLOT(exitManualMode(bool)));
	connect(ui.styledButtonHoseClampOpen, SIGNAL(clicked(bool)), this, SLOT(openHoseClamp(bool)));
	connect(ui.styledButtonInflationValveControl, SIGNAL(clicked(bool)), this, SLOT(openInflationValve(bool)));
	connect(ui.styledButtonMainTankValveOpen, SIGNAL(clicked(bool)), this, SLOT(openMainTankValve(bool)));
	connect(ui.styledButtonThrusterValveOpen, SIGNAL(clicked(bool)), this, SLOT(openThrusterValve(bool)));

	//make a parser to look after the files
	m_telemetryParser = new TelemetryParser(this);
	connect(m_telemetryParser, SIGNAL(dataChanged(InflationData)), this, SLOT(update(InflationData)));

	//initFiles();
	//m_serial = 0;
	//initPort();

	m_pollTimer = new QTimer(this);
	m_pollTimer->setInterval(100);
	connect(m_pollTimer, SIGNAL(timeout()), this, SLOT(readPort()));
	m_pollTimer->start();

//+++++++++++++++++++++++++++++++++++
//
	return;

	//debuggery
	QTimer* t = new QTimer(this);
	t->setInterval (333);
	t->start();
//	connect(t, SIGNAL(timeout()), this, SLOT(advanceWidgets()));

	messages
		<<"Earthlings, go home!"
		<<"We laugh at your technology, ha, ha."
		<<"Resistance is futile."
		<<"We'll be back."
		<<"You'll never get out of here inflated."
		<<"Caution: no inflated balloonery."
		<<"You call that a balloon! ha."
		<<"You'll need a Mars license #2041.22 to fly that thing around here."
		<<"Next tank station 150million kilometers; McDonalds next exit."
		<<""
		;
	//so that I can see the bottom half of the thing
//	this->move(0, -250);

}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
///
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
DlgInflation::~DlgInflation()
{

}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/// can be used by a user class to set the port for this class
///
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void DlgInflation::setSerialPort(QextSerialPort* port)
{
	//if assigned and open - close it 
	if(m_serial&&m_serial->isOpen ()){
		m_serial->close();
	}

	//if assigned delete it
	if(m_serial){
		delete m_serial;
		m_serial = 0;
	}

	//set the new one
	m_serial = port;

	return;
}




//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/// called from the telmetry parser every time it has new data
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void DlgInflation::update(InflationData data)
{
	ui.lblTank1Temperature->setText(QString::number(data.tank1Temperature, 'f', 0) + " K");
	ui.lblTank2Temperature->setText(QString::number(data.tank2Temperature, 'f', 0) + " K");
	ui.lblTank3Temperature->setText(QString::number(data.tank3Temperature, 'f', 0) + " K");

//	lblMissionTimeStamp->setNum(data.missionTimeStamp);
//	lblGeneralStatus->setText("I feel sick!");
//	lblInflationTime->setNum(data.inflationTime);

	ui.lblTankLinePressure->setNum(data.tankLinePressure);
	if(data.mainTankValveState)
		ui.lblTankValveState->setText(OPENED);
	else
		ui.lblTankValveState->setText(CLOSED);

	if(data.inflationControlValveState)
		ui.lblInflationControlValveState->setText(OPENED);
	else
		ui.lblInflationControlValveState->setText(CLOSED);

	ui.lblFeedPressureSensor->setNum(data.feedPressure);
	if(data.thrusterValveState)
		ui.lblThrusterValveState->setText(OPENED);
	else
		ui.lblThrusterValveState->setText(CLOSED);
	
	ui.lblEqualizationVolume1Temperature->setText(QString::number(data.equalizationVolume1Temperature, 'f', 0) + " K");
	ui.lblEqualizationVolume1Pressure->setNum(data.equalizationVolume1Pressure);
	ui.lblEqualizationVolume2Temperature->setText(QString::number(data.equalizationVolume2Temperature, 'f', 0) + " K");
	ui.lblEqualizationVolume2Pressure->setNum(data.equalizationVolume2Pressure);

	ui.lblInflationHosePressure->setNum(data.inflationHosePressure);
	ui.lblInflationHoseTemperature->setText(QString::number(data.inflationHoseTemperature, 'f', 0) + " K");
	if(data.inflationHoseClampState)
		ui.lblHoseClampState->setText(OPENED);
	else
		ui.lblHoseClampState->setText(CLOSED);

	ui.plotTankLinePressure->update(data.missionTimeStamp, data.tankLinePressure);
	ui.plotEqualizationVolume1Pressure->update(data.missionTimeStamp, data.equalizationVolume1Pressure);
	ui.plotEqualizationVolume2Pressure->update(data.missionTimeStamp, data.equalizationVolume2Pressure);
	ui.plotInflationHosePressure->update(data.missionTimeStamp, data.inflationHosePressure);
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
///used for initial debugging - making sure that data gets displayed properly
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void DlgInflation::advanceWidgets()
{
//making a InflationData structure here- 
	//reading in the data from the display, 
	//changing it and
	//putting back onto the display

	InflationData data;
	data.tank1Temperature = ui.lblTank1Temperature->text().toDouble()+1.0;//temperature in Kelvin
	data.tank2Temperature = ui.lblTank2Temperature->text().toDouble()+1.0;//temperature in Kelvin
	data.tank3Temperature = ui.lblTank3Temperature->text().toDouble()+1.0;//temperature in Kelvin

	data.missionTimeStamp = QTime::currentTime ().second() + QTime::currentTime ().minute()*60.0;//mission time in seconds
	data.generalStatus = 1;//an in to be converted to a text showing status "inflating"... need to be defined?
	data.inflationTime = data.missionTimeStamp/2;//inflation time in seconds

	data.tankLinePressure = ui.lblTankLinePressure->text().toDouble()+0.10;//pressure in bar

	if(ui.lblTankValveState->text()==OPENED)
		data.mainTankValveState = 1;
	else
		data.mainTankValveState = 0;

	if(ui.lblInflationControlValveState->text()==OPENED)
		data.inflationControlValveState = 1;
	else
		data.inflationControlValveState = 0;

	data.feedPressure = ui.lblFeedPressureSensor->text().toDouble() + 1.0;//pressure in bar

	if(ui.lblThrusterValveState->text()==OPENED)
		data.thrusterValveState = 1;
	else
		data.thrusterValveState = 0;

	data.equalizationVolume1Temperature = ui.lblEqualizationVolume1Temperature->text().toDouble()+1.0;//temperature in Kelvin
	data.equalizationVolume1Pressure = ui.lblEqualizationVolume1Pressure->text().toDouble()+1.0;//pressure in bar
	data.equalizationVolume2Temperature = ui.lblEqualizationVolume2Temperature->text().toDouble()+1.0;//temperature in Kelvin
	data.equalizationVolume2Pressure = ui.lblEqualizationVolume2Pressure->text().toDouble()+1.0;//pressure in bar - dispayed in mbar

	data.inflationHosePressure = ui.lblInflationHosePressure->text().toDouble()+1.0;//pressure in bar - dispayed in mbar
	data.inflationHoseTemperature = ui.lblInflationHoseTemperature->text().toDouble()+1.0;//temperature in Kelvin
//	data.inflationHoseClampState;// see GenericValveStates

	update(data);

	return;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/// called on button click
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void DlgInflation::exitManualMode(const bool exit)
{
	//QMessageBox::warning(this, "exitManualMode", "This will exit the manual mode");

	QWidget::close();

	return ;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/// called on button click
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void DlgInflation::openHoseClamp(const bool open)
{
	if(!m_serial->isOpen()){
		qDebug("DlgInflation::openHoseClamp(): m_serial not open");
//		return;
	}
	QString command;
	if(open)
		command = CommandHoseClampOpen;
	else
		command = CommandHoseClampClose;

	//QMessageBox::warning(this, "openThrusterValve", QString("command = '%1'").arg(command));
    ui.console->addOutput(command.left(command.length()-1));
	m_serial->write(command.toAscii().constData(), command.length());
	
	return ;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/// called on button click
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void DlgInflation::openInflationValve(const bool open)
{
	if(!m_serial->isOpen()){
		qDebug("DlgInflation::openInflationValve(): m_serial not open");
//		return;
	}
	QString command;
	if(open)
    {
        m_bSequenceOn = true;
        this->setFocus(Qt::OtherFocusReason);
        command = CommandStartSeq;
    }
	else
    {
		command = CommandAnyKey;
        m_bSequenceOn = false;
    }

	//QMessageBox::warning(this, "openThrusterValve", QString("command = '%1'").arg(command));
    ui.console->addOutput(command.left(command.length()-1));
	m_serial->write(command.toAscii().constData(), command.length());

	return ;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/// called on button click
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void DlgInflation::openMainTankValve(const bool open)
{
	if(!m_serial->isOpen()){
		qDebug("DlgInflation::openMainTankValve(): m_serial not open");
//		return;
	}
	QString command;
	if(open)
		command = CommandTankOpen;
	else
		command = CommandTankClose;

	//QMessageBox::warning(this, "openThrusterValve", QString("command = '%1'").arg(command));
    ui.console->addOutput(command.left(command.length()-1));
	m_serial->write(command.toAscii().constData(), command.length());

	return ;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/// called on button click
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void DlgInflation::openThrusterValve(const bool open)
{
	if(!m_serial->isOpen()){
		qDebug("DlgInflation::openThrusterValve(): m_serial not open");
//		return;
	}
	QString command;
	if(open)
		command = CommandThrusterOpen;
	else
		command = CommandThrusterClose;

	//QMessageBox::warning(this, "openThrusterValve", QString("command = '%1'").arg(command));
    ui.console->addOutput(command.left(command.length()-1));
	m_serial->write(command.toAscii().constData(), command.length());

	return ;
}

/*!
    \fn DlgInflation::QWidget::keyPressEvent ( QKeyEvent * event ) 
 */
void DlgInflation::keyPressEvent ( QKeyEvent * event ) 
{
    if(m_bSequenceOn)
    {
        QMessageBox::warning(this, "keyPressEvent", "keyPressEvent");
        openInflationValve(false);
    }
    
    if(event->key() != Qt::Key_Escape) event->ignore();
}



